<template>
  <!-- 选择坐席 -->
  <div :class="$style.selSeats">
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="groupId" label="业务组">
          <SearchSelectPicker
            url="/call-center/api/v1/businessGroup/page"
            placeholder="请选择所属业务组"
            lable-name="groupName"
            :value.sync="formData.groupId"
            :cur-options.sync="groupOption"
            multiple
            collapse-tags
            @selectChange="selectChangeHandle"
          ></SearchSelectPicker>
        </el-form-item>
        <el-form-item prop="accountNo" label="坐席姓名">
          <!-- <SearchSelectPicker
            :url="'/call-center/api/v1/businessGroup/member/page/'+formData.groupId"
            placeholder="请选择坐席姓名"
            value-name="accountNo"
            lable-name="staffName"
            must-pid
            :parent-id="formData.groupId"
            :value.sync="formData.accountNo"
            :lable.sync="staffName"
            clearable
          ></SearchSelectPicker> -->
          <SearchSelectPicker
            url="/call-center/api/v1/staffInfo/page"
            :other-raw="{groupNos:groupOption.map(e=>e.groupNo)}"
            placeholder="请选择执行坐席"
            value-name="accountNo"
            lable-name="staffName"
            :parent-id="formData.groupId"
            :value.sync="formData.accountNo"
            :lable.sync="staffName"
          ></SearchSelectPicker>
          <!-- <el-input v-model="formData.accountNo" placeholder="请输入坐席姓名" clearable /> -->
        </el-form-item>
        <el-form-item>
          <Button type="primary" enter @click="queryHandle">查询</Button>
        </el-form-item>
      </el-form>
    </FormContainer>
    <div class="button-container" style="padding:0">
      <Button type="primary" :loading="loading" @click="confrimAdd">确认添加</Button>
      <i></i>
      <Button type="primary" @click="next">下一步</Button>
    </div>
    <el-tabs v-model="active">
      <el-tab-pane name="1" label="待选择">
        <table-box
          ref="table"
          no-request
          :other-filters="otherFilters"
          :other-raw="otherRaw"
          :selected-arry="selectedAry"
          :table-config="tableConfig"
          @selection-change="selectionChange"
          @data-change="handlerDataChange"
        >
          <el-table-column slot="before" type="selection" width="50" align="center"></el-table-column>
        </table-box>
      </el-tab-pane>
      <el-tab-pane name="2" :label="`已选择(${selectedAry.length})`">
        <table-box
          no-request
          :table-config="tableConfig1"
          :data="selectedAry"
          @selection-change="selectionChange"
        >
        </table-box>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'

import { mapState, mapMutations } from 'vuex'
import { callBackTaskUpdate } from '@/api/callBackTask'
import SearchSelectPicker from '@/components/SearchSelectPicker'
export default {
  name: 'SelSeats',
  components: {
    FormContainer,
    Button,
    SearchSelectPicker
  },
  data() {
    return {
      active: '1',
      groupOption: [], // 当前选中的业务组
      staffName: '',
      formData: {
        groupId: [],
        accountNo: ''
      },
      otherFilters: [],
      otherRaw: {},
      addSuccess: false,
      loading: false,
      formRules: {
        // groupId: {
        //   required: true,
        //   message: '请选择业务组',
        //   trigger: 'blur'
        // }
      },
      selectedAry: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/staffInfo/page',
        sort: 'platformNo',
        order: 'desc',
        pageFlag: true,
        hideFuncBar: true,
        // tablePage: [100, 500, 1000, 2500, 5000],
        // pageSize: 100,
        // 表格字段动态配置
        setting: [
          {
            prop: 'accountNo',
            label: '坐席姓名',
            formatData: v => `${v.staffName}(${v.accountNo})`
          },
          {
            prop: 'groupName',
            label: '业务组'
          },
          {
            prop: 'deptName',
            label: '所属组织'
          }
        ]
      },
      tableConfig1: {
        hideFuncBar: true,
        // tablePage: [100, 500, 1000, 2500, 5000],
        // pageSize: 100,
        // 表格字段动态配置
        setting: [
          {
            prop: 'accountNo',
            label: '坐席姓名',
            formatData: v => `${v.staffName}(${v.accountNo})`
          },
          {
            prop: 'groupName',
            label: '业务组'
          },
          {
            prop: 'deptName',
            label: '所属组织'
          },
          {
            prop: 'operator',
            label: '操作',
            render: (h, row) => {
              return h('el-button', {
                props: {
                  type: 'text'
                },
                on: {
                  click: () => {
                    this.handlerRemoveSelect(row)
                  }
                }
              }, '删除')
            }
          }
        ]
      },
      tableData: []
    }
  },
  computed: {
    ...mapState({
      organization: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].basic.organization : ''
      },
      taskId: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].basic.id : ''
      },
      step: function(state) {
        return state.taskForm.form[this.$route.query.id] ? state.taskForm.form[this.$route.query.id].step : 1
      }
    })
  },
  methods: {
    ...mapMutations({
      SET_STEP: 'taskForm/SET_STEP'
    }),
    // 查询
    queryHandle() {
      if (!this.formData.accountNo && (this.formData.groupId && this.formData.groupId.length <= 0)) {
        this.$message.warning('请至少选择一项！')
        return
      }
      const list = []
      const otherRaw = {}
      if (this.formData.accountNo) {
        list.push({
          id: '',
          property: 'accountNo',
          value: this.formData.accountNo,
          operator: '='
        })
      }
      if (this.formData.groupId instanceof Array && this.formData.groupId.length > 0) {
        // list.push({
        //   id: '',
        //   property: 'groupIds',
        //   value: `[${this.formData.groupId.join(',')}]`,
        //   operator: 'in'
        // })
        otherRaw.groupIds = `[${this.formData.groupId.join(',')}]`
      }
      this.otherFilters = list
      this.otherRaw = otherRaw
      this.refreshTable('opCondition')
    },
    // 确认添加
    confrimAdd() {
      if (this.selectedAry.length === 0) {
        return this.$message.info('请至少选择一位坐席')
      }
      this.loading = true
      const ids = this.selectedAry.map(e => {
        return e.accountNo
      }).join(',')
      callBackTaskUpdate({
        id: this.taskId,
        callBackAgents: ids
      }).then(res => {
        this.loading = false
        if (res.success === 1) {
          this.$message.success('执行坐席添加成功')
          this.addSuccess = true
        }
      }).catch(er => {
        this.loading = false
      })
    },
    next() {
      if (!this.addSuccess) {
        return this.$message.info('请先添加执行坐席')
      }
      this.SET_STEP({ id: this.$route.query.id, step: this.step + 1 })
    },
    refreshTable(type) {
      // this.tableData = []
      this.$nextTick(() => {
        this.$refs.table.initTableData(type)
      })
    },
    selectionChange(val) {
      // this.selectedAry = val
      (val || []).forEach(e => {
        if (this.selectedAry.every(ee => ee.accountNo !== e.accountNo)) {
          this.selectedAry.push(e)
        }
      })
      this.tableData.forEach(r => {
        const i = this.selectedAry.findIndex(e => e.accountNo === r.accountNo)
        if (i >= 0 && val && val.every(e => e.accountNo !== r.accountNo)) {
          this.$refs.table && this.$refs.table.toggleRowSelection(r, false)
          this.selectedAry.splice(i, 1)
        }
      })
    },
    handlerDataChange(res) {
      this.tableData = res.data.records
      const t = this.tableData.filter(e => this.selectedAry.some(ee => ee.accountNo === e.accountNo))
      this.$nextTick(() => {
        t.forEach(e => {
          this.$refs.table && this.$refs.table.toggleRowSelection(e, true)
        })
      })
    },
    // 业务组变化
    selectChangeHandle() {
      this.accountNo = ''
      this.$set(this.formData, 'accountNo', '')
    },
    handlerRemoveSelect(row) {
      const i = this.selectedAry.findIndex(e => e.accountNo === row.accountNo)
      if (i >= 0) {
        this.selectedAry.splice(i, 1)
      }
      const t = this.tableData.find(e => e.accountNo === row.accountNo)
      if (t) {
        this.$refs.table && this.$refs.table.toggleRowSelection(t, false)
      }
    }
  }
}
</script>
<style lang='scss' module>
.selSeats{
  & tr{
    background-color: white !important;
  }
}
</style>
